<template>
  <div class="detail-wrapper">
    <el-page-header @back="goBack" content="生产详情"> </el-page-header>
    <!-- <el-divider></el-divider> -->
    <div class="topBox paddingBorder">
      <el-descriptions
        class="margin-top"
        :title="dataForm.name"
        :column="3"
        :labelStyle="labelStyle"
        :contentStyle="contentStyle"
        border
      >
        <template slot="extra">
          <el-button type="primary" size="small" @click="toEdit"
            >编辑</el-button
          >
          <el-button type="primary" size="small" @click="handleDelete"
            >删除</el-button
          >
        </template>
        <el-descriptions-item>
          <template slot="label"> 创建人 </template>
          {{ dataForm.add_user_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 创建时间 </template>
          {{ dataForm.add_time }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 最后修改人 </template>
          {{ dataForm.operator_user }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 修改时间 </template>
          {{ dataForm.operator_time }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <div class="top36 prodBox paddingBorder">
      <div class="titleLabel">生产信息</div>
      <el-descriptions
        class="margin-top top36"
        title="基本信息"
        :column="3"
        :labelStyle="labelStyle"
        :contentStyle="contentStyle"
        border
      >
        <el-descriptions-item>
          <template slot="label"> 生产单号 </template>
          {{ dataForm.production_serial }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 生产名称 </template>
          {{ dataForm.name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 单据日期 </template>
          {{ dataForm.bills_date }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 销售订单 </template>
          {{ dataForm.order_id }}
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template slot="label"> 负责人 </template>
          {{ dataForm.customer_manager }}
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template slot="label"> 备注 </template>
          {{ dataForm.remarks }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="descMockBox">
        <div class="descMockLabel">产品明细</div>
        <el-table
          :data="dataForm.production_sub"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            type="index"
            label="序号"
            header-align="center"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="product_name"
            label="产品"
            header-align="center"
            align="center"
            width="360"
          >
            <template slot-scope="scope">
              <div class="disCenter itemBox">
                <div class="imgBox">
                  <img :src="scope.row.product_master_pic" />
                </div>
                <div class="rightBox">
                  <el-tooltip
                    class="item"
                    effect="light"
                    :content="scope.row.product_name"
                    placement="top"
                  >
                    <span class="top overTwoHidden">{{
                      scope.row.product_name
                    }}</span>
                  </el-tooltip>

                  <span class="bottom"
                    >产品编号: {{ scope.row.product_serial }}</span
                  >
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sku_name"
            label="规格"
            header-align="center"
            align="center"
            width="200"
          >
          </el-table-column>
          <el-table-column
            prop="sale_num"
            label="销售数量"
            header-align="center"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="delivery_date"
            label="交付日期"
            header-align="center"
            align="center"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="planned_production"
            label="计划生产量"
            header-align="center"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="bom_name"
            label="BOM"
            header-align="center"
            align="center"
            width="280"
          >
          </el-table-column>
          <el-table-column
            prop="principal"
            label="负责人"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="sku_name"
            label="计划生产时间"
            header-align="center"
            width="280"
            align="center"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.plan_start }} ~ {{ scope.row.plan_end }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            header-align="center"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="scanBom(scope.row)"
                >查看BOM明细</el-button
              >
              <!-- <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
                >查看工艺流程</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 36px">
          <div class="disCenter" style="justify-content: flex-end">
            <div style="margin-right: 64px">合计</div>
            <div style="margin-right: 36px">
              计划生产总数量：
              <span class="mainColor storngTip">{{ tipTotal }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="descMockBox" style="margin-top: 0px !important">
        <div class="descMockLabel">消耗物料</div>
        <el-table
          :data="tableData"
          :span-method="objectSpanMethod"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            type="index"
            label="序号"
            header-align="center"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="supplier_name"
            label="执行单位"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="numCount"
            label="计划消耗数量"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="material_serial"
            label="物料编码"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="物料名称"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="specifications_model"
            label="规格型号"
            header-align="center"
            align="center"
          >
          </el-table-column>
        </el-table>
        <div style="margin: 21px 0 10px">
          <div class="disCenter" style="justify-content: flex-end">
            <div style="margin-right: 64px">合计</div>
            <div style="margin-right: 36px">
              计划消耗总数量：
              <span class="mainColor storngTip">{{ customTotal }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-backtop></el-backtop>
    <BomDetail
      v-if="bomVisible"
      ref="bomRef"
      @handleClose="handleBomClose"
      :bomRawSource="bomRawSource"
    ></BomDetail>
  </div>
</template>

<script>
import { addDynamicRoute } from '@/router'
import { getProductionDetail, deleteProduction } from '@/api'
import BomDetail from './sub-detail'
export default {
  components: {
    BomDetail,
  },
  data() {
    return {
      dataForm: {},
      labelStyle: {
        width: '150px',
      },
      contentStyle: {
        width: '28vw',
      },
      bomVisible: false,
      bomRawSource: {},
      tipTotal: 0,
      bomList: [],
      colFields: [
        'index',
        'supplier_name',
        'numCount',
        'material_serial',
        'name',
        'specifications_model',
      ],

      spanArr: [], //存储合并单元格的开始位置
      customTotal: 0,
      tableData: [],
    }
  },
  computed: {},
  activated() {
    const id = this.$route.params.id
    this.dataForm.id = id
    this.tableData = []
    this.spanArr = []
    if (id) this.fetchDetail(id)
  },
  watch: {
    tableData: {
      handler() {
        this.calcCustomTotal()
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    calcCustomTotal() {
      if (this.tableData.length < 1) return
      this.customTotal = this.tableData.reduce((pre, cur) => {
        return pre + Number(cur.num)
      }, 0)
    },
    transBomCustomList() {
      console.log(this.dataForm.production_sub)
      // 删除未绑定数据
      const list = this.dataForm.production_sub
      // debugger;
      if (list.length > 0) {
        let temp = []
        for (let i = 0; i < list.length; i++) {
          let arr = []
          let bom_sub_list = list[i].bom_list
          bom_sub_list.forEach((item) =>
            arr.push({
              material_serial: item.material_serial,
              name: item.name,
              specifications_model: item.specifications_model,
            })
          )

          // let fill_bom_sub_list = list[i].fill_bom_sub;
          bom_sub_list.forEach((it, idx) => {
            let info = arr[idx]
            console.log(it)
            let fitList = it?.execute_list || []
            fitList &&
              fitList.forEach((itS) => {
                temp.push({
                  supplier_id: itS?.supplier_id || '',
                  num: Number(itS.num),
                  supplier_name: itS?.supplier_name || '',
                  ...info,
                })
              })
          })
        }
        console.log(temp)
        const filterList = temp.filter((item) => item.num > 0)
        // 供应商 id 去重
        let tempIds = []
        filterList.forEach((item) => {
          tempIds.push(item.supplier_id)
        })

        let combineObj = {}
        const unique = [...new Set(tempIds)]
        // debugger;
        console.log(filterList)
        for (let i = 0; i < unique.length; i++) {
          // 当前id匹配项
          let targetList = filterList.filter(
            (item) => item.supplier_id === unique[i]
          )
          let count = targetList.reduce((pre, cur) => {
            return pre + Number(cur.num)
          }, 0)
          targetList.forEach((item) => (item.numCount = count))
          combineObj[i] = targetList
        }

        let sortList = []
        for (let key in combineObj) {
          sortList = [...sortList, ...combineObj[key]]
        }
        console.log(combineObj)
        console.log(sortList)
        this.tableData = sortList
        // this.computeCell(this.tableData);
        this.getSpanArr()
      }
    },
    getSpanArr() {
      for (let i = 0; i < this.tableData.length; i++) {
        let row = i
        // let col = i % this.colCount;
        if (row === 0) {
          // i 表示行 j表示列
          for (let j = 0; j < this.colFields.length; j++) {
            this.spanArr[i * this.colFields.length + j] = {
              rowspan: 1,
              colspan: 1,
            }
          }
        } else {
          for (let j = 0; j < this.colFields.length; j++) {
            // 当前和上一次的一样
            //  合并所有列的相同数据单元格
            if (
              this.colFields[j] === 'supplier_name' ||
              this.colFields[j] === 'numCount'
            ) {
              // 指定合并哪些列

              if (
                this.tableData[row]['supplier_name'] !==
                this.tableData[row - 1]['supplier_name']
              ) {
                // 哪些不合并:School不一样的,不合并
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1,
                  colspan: 1,
                }
              } else if (
                this.tableData[row][this.colFields[j]] ===
                this.tableData[row - 1][this.colFields[j]]
              ) {
                let beforeItem = this.spanArr[
                  (row - 1) * this.colFields.length + j
                ]
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1 + beforeItem.rowspan, // 合并几列
                  colspan: 1, // 合并几行
                }
                beforeItem.rowspan = 0
                beforeItem.colspan = 0
              } else {
                // rowspan 和 colspan 都为1表格此单元格不合并
                this.spanArr[row * this.colFields.length + j] = {
                  rowspan: 1,
                  colspan: 1,
                }
              }
            }
          }
        }
      }
      // 对数据进行倒序
      let stack = []

      for (let i = 0; i < this.colFields.length; i++) {
        for (let j = 0; j < this.tableData.length; j++) {
          // console.log("i=" + i + " j=" + j);
          // i 表示列 j表示行
          if (j === 0) {
            if (this.spanArr[j * this.colFields.length + i]?.rowspan === 0) {
              stack.push(this.spanArr[j * this.colFields.length + i])
            }
          } else {
            if (this.spanArr[j * this.colFields.length + i]?.rowspan === 0) {
              stack.push(this.spanArr[j * this.colFields.length + i])
            } else {
              stack.push(this.spanArr[j * this.colFields.length + i])
              while (stack.length > 0) {
                let pop = stack.pop()
                let len = stack.length
                this.spanArr[(j - len) * this.colFields.length + i] = pop
              }
            }
          }
        }
      }
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      return this.spanArr[rowIndex * this.colFields.length + columnIndex]
    },
    calcTotal(data) {
      if (data && data.length < 1) return
      this.tipTotal = data.reduce((pre, cur) => {
        return pre + Number(cur.planned_production)
      }, 0)
    },
    handleBomClose() {
      this.bomVisible = false
    },
    async scanBom(row) {
      console.log(row)
      this.bomVisible = true
      this.bomRawSource = row
    },
    async handleDelete() {
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await deleteProduction({ id: this.dataForm.id })
          if (res?.status === 1) {
            this.$message.success(res?.msg || '')
            this.$router.go(-1)
          }
        })
        .catch(() => {})
    },
    async fetchDetail(id) {
      const params = {
        id,
      }
      const res = await getProductionDetail(params)
      console.log(res)
      if (res?.status === 1) {
        const data = res?.data || {}
        this.dataForm = data
        this.bomList = res?.total_execute_list || []

        this.calcTotal(this.dataForm.production_sub)
        console.log(data)
        this.transBomCustomList()
      }
    },
    goBack() {
      this.$router.go(-1)
    },
    toEdit() {
      const routeParams = {
        routeName: `manufacturing-plan__edit`,
        title: `生产计划 - 编辑`,
        path: 'manufacturing/plan-add',
        params: {
          id: this.dataForm.id || '',
        },
      }
      addDynamicRoute(routeParams, this.$router)
    },
  },
}
</script>

<style lang="scss" scoped>
.detail-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title,
  .el-page-header__content {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }

  .topBox {
    margin-top: 36px;
    ::v-deep .el-descriptions__title {
      font-size: 20px;
      font-weight: 600;
      position: relative;
      padding-left: 16px;
      color: #303133;
      &::before {
        background: $mainColor;
        content: '';
        display: inline-block;
        height: 20px;
        left: 0;
        position: absolute;
        top: calc(50% - 10px);
        width: 3px;
      }
    }
  }

  .prodBox {
    .prodImgBox {
      .imgItem {
        width: 64px;
        height: 64px;
        margin-left: 12px;
        cursor: pointer;
        &:first-child {
          margin-left: 0;
        }
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .itemBox {
    .imgBox {
      width: 64px;
      height: 64px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .rightBox {
      margin-left: 14px;
      text-align: left;
      .top {
        max-width: 200px;
        margin-bottom: 6px;
      }
    }
  }
}
</style>

<style lang="scss">
::v-deep .el-page-header__title {
  font-size: 12px;
}
</style>
